﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;

namespace BrokerBase.Lib.Tool
{
    public static class TransportUtil
    {
        /// <summary>
        /// 压缩一个文本
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static byte[] CompressText(string text)
        {
            MemoryStream ms = null;
            DeflateStream stream = null;

            try
            {
                System.Text.Encoding encoding = System.Text.Encoding.Unicode;
                byte[] buffer = encoding.GetBytes(text);

                ms = new System.IO.MemoryStream();
                stream = new DeflateStream(ms, CompressionMode.Compress, true);
                stream.Write(buffer, 0, buffer.Length);
                stream.Close();
                stream.Dispose();

                buffer = ms.ToArray();
                ms.Close();

                return buffer;
            }
            catch (Exception er)
            {
                throw er;
            }
            finally
            {
                stream.Dispose();
                ms.Dispose();
            }
        }
        /// <summary>
        /// 解压缩一个二进制数据到文本
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string DecompressText(byte[] data)
        {

            MemoryStream ms = new MemoryStream();
            MemoryStream ms2 = new MemoryStream(data);

            DeflateStream ds = new DeflateStream(ms2, CompressionMode.Decompress);
            ds.Flush();
            ds.CopyTo(ms);

            byte[] buffer = ms.ToArray();

            System.Text.Encoding encoding = System.Text.Encoding.Unicode;

            string s = encoding.GetString(buffer);

            return s;
        }
    }
}
